<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Archives;

use Think\Exception;
use Think\Log;

class Archives extends \Service\Common\BaseModel
{
    protected $name = 'eyes_archives';

    public $relate = [
        '1' =>'自己',
        '2' =>'父母',
        '3' =>'孩子',
        '4' =>'爱人',
        '5' =>'朋友',
        '6' =>'同事',
        '7' =>'其他',
    ];

    public $sex = [
        '1' => '男',
        '2' => '女',
    ];
    //列表
    public function lists($uid, $page_num, $page_size)
    {
        $where = [
            'userid' => $uid,
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        return [
            $this->format($list),
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function archiveAdd($uid, $param){
        if($param['relation'] == 1){
            $flag = M('eyes_archives')->where(['relation' =>1,'userid' => $uid])->find();
            if($flag) throw new Exception('自己的档案已添加');
        }
        $add = [
            'userid' => $uid,
            'name' => $param['name'],
            'sex' => $param['sex'],
            'relation' => $param['relation'],
            'birthday' => $param['birthday'],
        ];
        $flag = $this->add($add);

        if($flag){
            $flag1 = M('eyes_task_log')->where(['taskid' => 5, 'userid' => $uid, 'record_date' => date('Y-m-d')])->find();
            if(!$flag1) OE('user')->addEyesMoney($uid, 5);
            return $flag;
        }else{
            throw new Exception('添加失败');
        }
    }

    public function archiveDetail($uid, $param){
        $flag = M('eyes_archives')->where(['id' =>$param['id'],'userid' => $uid])->find();
        if($flag){
            return $this->format($flag);
        }else{
            throw new Exception('查询失败');
        }
    }


    //格式化
    public function format($list)
    {
        if (!$list) {
            return $list;
        }

        $is_one = count($list) == count($list, 1);
        $list = $is_one ? [$list] : $list;

        foreach ($list as &$row) {
            $row['relation_label'] = $this->relate[$row['relation']];
        }
        return $is_one ? $list[0] : $list;
    }



}